
package com.itmayiedu.service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private ValueOperations opsForValue = stringRedisTemplate.opsForValue();
    private ListOperations opsForList = stringRedisTemplate.opsForList();
    private SetOperations opsForSet = stringRedisTemplate.opsForSet();


    public void setString(String key, String value) {
        this.setObject(key, value, null);
    }

    public void setString(String key, String value, Long time) {
        this.setObject(key, value, time);
    }

    public void setList(String key, List<String> value) {
        this.setObject(key, value, null);
    }

    public void setList(String key, List<String> value, Long time) {
        this.setObject(key, value, time);
    }

    private void setObject(String key, Object value, Long time) {
        if (StringUtils.isEmpty(key) || value == null) {
            return;
        }
        //判断类型 存放String类型
        if (value instanceof String) {
            String strValue = (String) value;
            opsForValue.set(key, strValue);
            this.expire(key,time);
            return;
        }
        //判断类型 存放list类型
        if (value instanceof List) {
            List<String> listValue = (List<String>) value;
            opsForList.leftPushAll(key, listValue);
            this.expire(key,time);
            return;
        }
        //判断类型 存放set类型
        if (value instanceof Set) {
            Set<String> setValue = (Set<String>) value;
            opsForSet.add(key, setValue);
            this.expire(key,time);
            return;
        }


    }

    //设置过期时间
    private void expire(String key, Long time) {
        if (time != null) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    public String getString(String key) {
        return (String) opsForValue.get(key);
    }

    public List<String> getList(String key) {
        return (List<String>) opsForList.leftPop(key);
    }
}
